package com.region.spring.cloud.core.configure;

import com.region.common.adapter.logging.LoggerAdapter;
import com.region.common.adapter.logging.LoggerAdapterFactory;
import com.region.http.client.RegionHttpClient;
import com.region.loadbalancer.group.Server;
import com.region.loadbalancer.monitor.stat.DetectionConnection;
import com.region.spring.cloud.core.common.CloudServerStatus;

import java.util.Map;
import java.util.Objects;

/**
 * @author liujieyu
 * @date 2024/10/21 19:08
 * @desciption
 */
public class SpringCloudDetectionConnection implements DetectionConnection {

    private static final LoggerAdapter loggerAdapter = LoggerAdapterFactory.getLogger(SpringCloudDetectionConnection.class);

    private static final String HEALTH_URL = "/actuator/health";

    @Override
    public boolean connect(Server server) {
        try {
            StringBuilder requestUrl = new StringBuilder();
            requestUrl.append(server.getServerAllInfo());
            requestUrl.append(HEALTH_URL);
            Map data = RegionHttpClient.get(requestUrl.toString()).execute(Map.class);
            return Objects.equals(CloudServerStatus.UP.getStatus(), String.valueOf(data.get("status")));
        } catch (Throwable t) {
            loggerAdapter.error("The " + server + " detect error.");
        }
        return false;
    }
}
